<!DOCTYPE html>
<html lang="en">
  <head>
    <title>
        Java-framework-SpringCloud-3 - rulerLwx Blog
      </title>
        <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-transform" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no,email=no,adress=no">
    
    <meta name="theme-color" content="#000000" />
    
    <meta http-equiv="window-target" content="_top" />
    
    
    <meta name="description" content="概述 子模块介绍： microservicecloud-api API公共模块，如：公共实体类 microservicecloud-consumer-dept-80 microservicecloud-eureka-7001 服务注册中心 microservicecloud-eureka-7002 microservicecloud-eureka-7003 microservicecloud-provider-dept-8001 服务提供者 microservicecloud-provider-dept-8002 microservicecloud-provider-dept-8003 数据库数据 DROP DATABASE IF EXISTS cloudDB01; CREATE DATABASE cloudDB01 CHARACTER SET UTF8; USE cloudDB01; CREATE TABLE dept ( deptno BIGINT NOT NULL PRIMARY KEY" />
    <meta name="generator" content="Hugo 0.73.0 with theme pure" />
    <title>Java-framework-SpringCloud-3 - rulerLwx Blog</title>
    
    
    <link rel="stylesheet" href="https://rulerLwx.gitee.io/css/style.min.c4bc7071f132c964c2116bca53b392933f377e5ca7b7051ed245187c621a2d3e.css">
    
    <link rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/9.15.10/styles/github.min.css" async>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.css" async>
    <meta property="og:title" content="Java-framework-SpringCloud-3" />
<meta property="og:description" content="概述 子模块介绍： microservicecloud-api API公共模块，如：公共实体类 microservicecloud-consumer-dept-80 microservicecloud-eureka-7001 服务注册中心 microservicecloud-eureka-7002 microservicecloud-eureka-7003 microservicecloud-provider-dept-8001 服务提供者 microservicecloud-provider-dept-8002 microservicecloud-provider-dept-8003 数据库数据 DROP DATABASE IF EXISTS cloudDB01; CREATE DATABASE cloudDB01 CHARACTER SET UTF8; USE cloudDB01; CREATE TABLE dept ( deptno BIGINT NOT NULL PRIMARY KEY" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://rulerLwx.gitee.io/2020/07/java-framework-springcloud-3/" />
<meta property="article:published_time" content="2020-07-01T18:58:47+08:00" />
<meta property="article:modified_time" content="2020-07-01T18:58:47+08:00" />
<meta itemprop="name" content="Java-framework-SpringCloud-3">
<meta itemprop="description" content="概述 子模块介绍： microservicecloud-api API公共模块，如：公共实体类 microservicecloud-consumer-dept-80 microservicecloud-eureka-7001 服务注册中心 microservicecloud-eureka-7002 microservicecloud-eureka-7003 microservicecloud-provider-dept-8001 服务提供者 microservicecloud-provider-dept-8002 microservicecloud-provider-dept-8003 数据库数据 DROP DATABASE IF EXISTS cloudDB01; CREATE DATABASE cloudDB01 CHARACTER SET UTF8; USE cloudDB01; CREATE TABLE dept ( deptno BIGINT NOT NULL PRIMARY KEY">
<meta itemprop="datePublished" content="2020-07-01T18:58:47&#43;08:00" />
<meta itemprop="dateModified" content="2020-07-01T18:58:47&#43;08:00" />
<meta itemprop="wordCount" content="3163">



<meta itemprop="keywords" content="" /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Java-framework-SpringCloud-3"/>
<meta name="twitter:description" content="概述 子模块介绍： microservicecloud-api API公共模块，如：公共实体类 microservicecloud-consumer-dept-80 microservicecloud-eureka-7001 服务注册中心 microservicecloud-eureka-7002 microservicecloud-eureka-7003 microservicecloud-provider-dept-8001 服务提供者 microservicecloud-provider-dept-8002 microservicecloud-provider-dept-8003 数据库数据 DROP DATABASE IF EXISTS cloudDB01; CREATE DATABASE cloudDB01 CHARACTER SET UTF8; USE cloudDB01; CREATE TABLE dept ( deptno BIGINT NOT NULL PRIMARY KEY"/>

    <!--[if lte IE 9]>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
      <![endif]-->

    <!--[if lt IE 9]>
        <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
      <![endif]-->
  </head>

  
  

  <body class="main-center theme-black" itemscope itemtype="http://schema.org/WebPage"><header class="header" itemscope itemtype="http://schema.org/WPHeader">
    <div class="slimContent">
      <div class="navbar-header">
        <div class="profile-block text-center">
          <a id="avatar" href="https://gitee.com/rulerLwx" target="_blank">
            <img class="img-circle img-rotate" src="https://rulerLwx.gitee.io/avatar.png" width="200" height="200">
          </a>
          <h2 id="name" class="hidden-xs hidden-sm">rulerLwx</h2>
          <h3 id="title" class="hidden-xs hidden-sm hidden-md">thinking...</h3>
          <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i>Guangzhou, China</small>
        </div><div class="search" id="search-form-wrap">
    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="Search" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i
                        class="icon icon-search"></i></button>
            </span>
        </div>
        <div class="ins-search">
            <div class="ins-search-mask"></div>
            <div class="ins-search-container">
                <div class="ins-input-wrapper">
                    <input type="text" class="ins-search-input" placeholder="Type something..."
                        x-webkit-speech />
                    <button type="button" class="close ins-close ins-selectable" data-dismiss="modal"
                        aria-label="Close"><span aria-hidden="true">×</span></button>
                </div>
                <div class="ins-section-wrapper">
                    <div class="ins-section-container"></div>
                </div>
            </div>
        </div>
    </form>
</div>
        <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
      </div>
      <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
        <ul class="nav navbar-nav main-nav">
            <li class="menu-item menu-item-home">
                <a href="/">
                    <i class="icon icon-home-fill"></i>
                  <span class="menu-title">Home</span>
                </a>
            </li>
            <li class="menu-item menu-item-archives">
                <a href="/posts/">
                    <i class="icon icon-archives-fill"></i>
                  <span class="menu-title">Archives</span>
                </a>
            </li>
            <li class="menu-item menu-item-categories">
                <a href="/categories/">
                    <i class="icon icon-folder"></i>
                  <span class="menu-title">Categories</span>
                </a>
            </li>
            <li class="menu-item menu-item-tags">
                <a href="/tags/">
                    <i class="icon icon-tags"></i>
                  <span class="menu-title">Tags</span>
                </a>
            </li>
            <li class="menu-item menu-item-about">
                <a href="/about/">
                    <i class="icon icon-cup-fill"></i>
                  <span class="menu-title">About</span>
                </a>
            </li>
        </ul>
      </nav>
    </div>
  </header>

<aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">Board</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">enjoy~
            </div>
        </div>
    </div>
</div>

      <div class="widget">
    <h3 class="widget-title"> Categories</h3>
    <div class="widget-body">
        <ul class="category-list">
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-framework/" class="category-list-link">java-framework</a><span class="category-list-count">38</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-front-end/" class="category-list-link">java-front-end</a><span class="category-list-count">11</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-se/" class="category-list-link">java-se</a><span class="category-list-count">21</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-senior/" class="category-list-link">java-senior</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/linux/" class="category-list-link">linux</a><span class="category-list-count">13</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/tools/" class="category-list-link">tools</a><span class="category-list-count">1</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%8A%80%E6%9C%AF%E6%9D%82%E7%83%A9/" class="category-list-link">技术杂烩</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" class="category-list-link">数据库</a><span class="category-list-count">15</span></li>
        </ul>
    </div>
</div>
      <div class="widget">
    <h3 class="widget-title"> Tags</h3>
    <div class="widget-body">
        <ul class="tag-list">
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/jvm/" class="tag-list-link">jvm</a><span
                    class="tag-list-count">1</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" class="tag-list-link">多线程</a><span
                    class="tag-list-count">2</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" class="tag-list-link">网络编程</a><span
                    class="tag-list-count">3</span></li>
            
        </ul>

    </div>
</div>
      
<div class="widget">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget-body">
        <ul class="recent-post-list list-unstyled no-thumbnail">
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%87%AA%E5%B7%B1%E5%8A%A8%E6%89%8B%E4%B8%80%E6%89%B9%E9%87%8F%E7%A7%BB%E5%8A%A8%E9%87%8D%E5%91%BD%E5%90%8D%E6%96%87%E4%BB%B6/" class="title">自己动手（一）——批量移动、重命名文件</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-27 17:50:02 &#43;0800 CST" itemprop="datePublished">2020-07-27</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E5%85%B3%E4%BA%8Einteger%E7%9A%84-128~127%E7%BC%93%E5%AD%98/" class="title">关于Integer的 -128~127缓存</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-11 16:56:21 &#43;0800 CST" itemprop="datePublished">2020-07-11</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98/" class="title">跨域问题</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-08 22:41:12 &#43;0800 CST" itemprop="datePublished">2020-07-08</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E4%B8%AA%E4%BA%BA%E5%8D%9A%E5%AE%A2%E6%90%AD%E5%BB%BA/" class="title">个人博客搭建</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-05 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-05</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/centos/" class="title">CentOS-</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-01 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-01</time>
                    </p>
                </div>
            </li>
        </ul>
    </div>
</div>
  </div>
</aside>

    
    
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <h4 class="toc-title">Catalogue</h4>
    <nav id="toc" class="js-toc toc">

    </nav>
  </div>
</aside>
<main class="main" role="main"><div class="content">
  <article id="-" class="article article-type-" itemscope
    itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      <h1 itemprop="name">
  <a
    class="article-title"
    href="/2020/07/java-framework-springcloud-3/"
    >Java-framework-SpringCloud-3</a
  >
</h1>

      <div class="article-meta">
        
<span class="article-date">
  <i class="icon icon-calendar-check"></i>&nbsp;
<a href="https://rulerLwx.gitee.io/2020/07/java-framework-springcloud-3/" class="article-date">
  <time datetime="2020-07-01 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-01</time>
</a>
</span>
<span class="article-category">
  <i class="icon icon-folder"></i>&nbsp;
  <a class="article-category-link" href="/categories/java-framework/"> Java-framework </a>
</span>

        <span class="post-comment"><i class="icon icon-comment"></i>&nbsp;<a href="/2020/07/java-framework-springcloud-3/#comments"
            class="article-comment-link">Comments</a></span>
		<span class="post-wordcount hidden-xs" itemprop="wordCount">Word Count: 3163words</span>
		<span class="post-readcount hidden-xs" itemprop="timeRequired">Read Count: 7minutes </span>
      </div>
    </div>
    <div class="article-entry marked-body js-toc-content" itemprop="articleBody">
      <h1 id="概述">概述</h1>
<p>子模块介绍：</p>
<ul>
<li>microservicecloud-api API公共模块，如：公共实体类</li>
<li>microservicecloud-consumer-dept-80</li>
<li>microservicecloud-eureka-7001 服务注册中心</li>
<li>microservicecloud-eureka-7002</li>
<li>microservicecloud-eureka-7003</li>
<li>microservicecloud-provider-dept-8001 服务提供者</li>
<li>microservicecloud-provider-dept-8002</li>
<li>microservicecloud-provider-dept-8003</li>
</ul>
<h1 id="数据库数据">数据库数据</h1>
<pre><code>DROP DATABASE IF EXISTS cloudDB01;
CREATE DATABASE cloudDB01 CHARACTER SET UTF8;
USE cloudDB01;
CREATE TABLE dept
(
  deptno BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  dname VARCHAR(60),
  db_source   VARCHAR(60)
);
 
INSERT INTO dept(dname,db_source) VALUES('开发部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('人事部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('财务部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('市场部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('运维部',DATABASE());
 
SELECT * FROM dept;
</code></pre>
<p>Rest 客户端</p>
<pre><code class="language-java">    /**
     * 使用 使用restTemplate访问restful接口非常的简单粗暴无脑。 (url, requestMap,
     * ResponseBean.class)这三个参数分别代表 REST请求地址、请求参数、HTTP响应转换被转换成的对象类型。
     */
    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value = &quot;/consumer/dept/add&quot;)
    public boolean add(Dept dept)
    {
        return restTemplate.postForObject(REST_URL_PREFIX + &quot;/dept/add&quot;, dept, Boolean.class);
    }
</code></pre>
<h1 id="eureka-服务中心">Eureka 服务中心</h1>
<p>1）新建 microservicecloud-eureka-7001 模块</p>
<p>2）maven 导入依赖</p>
<pre><code class="language-xml">        &lt;!--eureka-server服务端 --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-starter-eureka-server&lt;/artifactId&gt;
        &lt;/dependency&gt;
</code></pre>
<p>3）yml 配置文件</p>
<pre><code class="language-yml">server: 
  port: 7001
 
eureka: 
  instance:
    hostname: eureka7001.com #eureka服务端的实例名称
  client: 
    register-with-eureka: false     #false表示不向注册中心注册自己。
    fetch-registry: false     #false表示自己端就是注册中心，我的职责就是维护服务实例，并不需要去检索服务
    service-url: 
      #单机 defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/       #设置与Eureka Server交互的地址查询服务和注册服务都需要依赖这个地址（单机）。
      defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
</code></pre>
<p>4）入口类开启 eureka 服务</p>
<pre><code class="language-java">@SpringBootApplication
@EnableEurekaServer // EurekaServer服务器端启动类,接受其它微服务注册进来
public class EurekaServer7001_App
{
	public static void main(String[] args)
	{
		SpringApplication.run(EurekaServer7001_App.class, args);
	}
}
</code></pre>
<h1 id="修改-microservicecloud-provider-dept-8001">修改 microservicecloud-provider-dept-8001</h1>
<p>让 microservicecloud-provider-dept-8001 作为 eureka 客户端，注册到上面的7001中</p>
<h1 id="微服务信息完善">微服务信息完善</h1>
<p>以下配置是优化微服务，显示实例名、IP、相关服务信息：</p>
<p>1）添加依赖包：</p>
<pre><code class="language-xml">    &lt;!-- actuator监控信息完善 --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;
    &lt;/dependency&gt;
</code></pre>
<p>2）完善<code>microservicecloud-provider-dept-8001</code>的application.yml配置</p>
<pre><code class="language-properties">eureka:
  client: #客户端注册进eureka服务列表内
    service-url:
      #defaultZone: http://localhost:7001/eureka
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
# 以下信息是优化微服务，显示实例名、IP、相关服务信息
  instance:
    instance-id: microservicecloud-dept8001
    prefer-ip-address: true     #访问路径可以显示IP地址
info:
  app.name: atguigu-microservicecloud
  company.name: www.atguigu.com
  build.artifactId: $project.artifactId$
  build.version: $project.version$
</code></pre>
<p>3）在总的父工程pom中添加以下构建信息：</p>
<pre><code class="language-xml">&lt;build&gt;
   &lt;finalName&gt;microservicecloud&lt;/finalName&gt;
   &lt;resources&gt;
     &lt;resource&gt;
       &lt;directory&gt;src/main/resources&lt;/directory&gt;
       &lt;filtering&gt;true&lt;/filtering&gt;
     &lt;/resource&gt;
   &lt;/resources&gt;
   &lt;plugins&gt;
     &lt;plugin&gt;
       &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
       &lt;artifactId&gt;maven-resources-plugin&lt;/artifactId&gt;
       &lt;configuration&gt;
         &lt;delimiters&gt;
          &lt;delimit&gt;$&lt;/delimit&gt;
         &lt;/delimiters&gt;
       &lt;/configuration&gt;
     &lt;/plugin&gt;
   &lt;/plugins&gt;
  &lt;/build&gt;
</code></pre>
<p>图解：</p>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img-07/20200708113552.png" alt="image"></p>
<h1 id="eureka集群">Eureka集群</h1>
<p>新建<code>microservicecloud-eureka-7002</code>和<code>microservicecloud-eureka-7003</code>模块</p>
<p>1）依赖</p>
<p>参考<code>microservicecloud-eureka-7001</code>的pom</p>
<p>2）修改7002、7003启动类开启注册服务</p>
<p>3）修改7002、7003的yml配置文件</p>
<pre><code class="language-yml">server: 
  port: 7002
 
eureka: 
  instance:
    hostname: eureka7002.com #eureka服务端的实例名称
  client: 
    register-with-eureka: false     #false表示不向注册中心注册自己。
    fetch-registry: false     #false表示自己端就是注册中心，我的职责就是维护服务实例，并不需要去检索服务
    service-url:
      #设置与Eureka Server交互的地址，查询服务和注册服务都需要依赖这个地址（单机）。
      #defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7003.com:7003/eureka/
</code></pre>
<p>4）修改host文件</p>
<pre><code>127.0.0.1 eureka7001.com
127.0.0.1 eureka7002.com
127.0.0.1 eureka7003.com
</code></pre>
<p>5）修改其它微服务提供者、消费者的yml，使其指向上面的3个服务注册中心</p>
<pre><code class="language-yml">eureka:
  client: #客户端注册进eureka服务列表内
    service-url:
      #defaultZone: http://localhost:7001/eureka
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/

</code></pre>
<p>程序员级别：</p>
<p>码神》码龙》码牛》码工》码农》码畜》码渣</p>
<p>p3-p9</p>
<h1 id="ribbon负载均衡">Ribbon负载均衡</h1>
<h2 id="概述-1">概述</h2>
<p>Spring Cloud Ribbon是基于Netflix Ribbon实现的一套<strong>客户端</strong>负载均衡的工具</p>
<p>LB，即负载均衡(Load Balance)，在微服务或分布式集群中经常用的一种应用。</p>
<p>负载均衡简单的说就是将用户的请求平摊的分配到多个服务上，从而达到系统的HA。</p>
<p>常见的负载均衡有软件Nginx，LVS，硬件F5等。</p>
<p>官网：https://github.com/Netflix/ribbon</p>
<h2 id="入门改造microservicecloud-consumer-dept-80模块">入门——改造<code>microservicecloud-consumer-dept-80</code>模块</h2>
<p>1）pom</p>
<pre><code class="language-xml">    &lt;!-- Ribbon相关 --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
        &lt;artifactId&gt;spring-cloud-starter-eureka&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
        &lt;artifactId&gt;spring-cloud-starter-ribbon&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
        &lt;artifactId&gt;spring-cloud-starter-config&lt;/artifactId&gt;
    &lt;/dependency&gt;
</code></pre>
<p>2）@LoadBalanced</p>
<p>在配置类的bean上使用<code>@LoadBalanced</code>注解</p>
<p>因为，Spring Cloud Ribbon是基于Netflix Ribbon实现的一套<strong>客户端</strong>负载均衡的工具</p>
<pre><code class="language-java">@Configuration
public class ConfigBean {
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate()
    {
        return new RestTemplate();
    }
}
</code></pre>
<p>3）启动类</p>
<pre><code class="language-java">@SpringBootApplication
@EnableEurekaClient
//在启动该微服务的时候就能去加载我们的自定义Ribbon配置类，从而使配置生效
//@RibbonClient(name=&quot;MICROSERVICECLOUD-DEPT&quot;,configuration=MySelfRule.class)
//@RibbonClient(name=&quot;MICROSERVICECLOUD-DEPT&quot;,configuration=MySelfRule.class)
public class DeptConsumer80_App
{
	public static void main(String[] args)
	{
		SpringApplication.run(DeptConsumer80_App.class, args);
	}
}
</code></pre>
<p>4）控制层根据微服务实例名称调用</p>
<pre><code class="language-java">@RestController
public class DeptController_Consumer {
    //private static final String REST_URL_PREFIX = &quot;http://localhost:8001&quot;;
    private static final String REST_URL_PREFIX = &quot;http://MICROSERVICECLOUD-DEPT&quot;;
    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value = &quot;/consumer/dept/list&quot;)
    public List&lt;Dept&gt; list()
    {
        return restTemplate.getForObject(REST_URL_PREFIX + &quot;/dept/list&quot;, List.class);
    }
</code></pre>
<p>说明：微服务实例名称指的是yml的<code>spring:application:name: microservicecloud-dept</code>，也就是下面的服务名</p>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img-07/20200708142229.png" alt=""></p>
<p>5）测试</p>
<p>启动以下服务：</p>
<ul>
<li>microservicecloud-eureka-7001</li>
<li>microservicecloud-eureka-7002</li>
<li>microservicecloud-provider-dept-8001</li>
<li>microservicecloud-consumer-dept-80</li>
</ul>
<p>浏览器访问：http://localhost/consumer/dept/list</p>
<p>6）总结</p>
<p>使用微服务实例名访问就不用记住服务的地址、端口</p>
<h2 id="负载均衡">负载均衡</h2>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img-07/20200708113751.png" alt="image"></p>
<p>1）基于8001新建模块</p>
<ul>
<li>microservicecloud-provider-dept-8002</li>
<li>microservicecloud-provider-dept-8003</li>
</ul>
<p>2）新建8002、8003对应的数据库</p>
<pre><code class="language-sql">DROP DATABASE IF EXISTS cloudDB02;
 
CREATE DATABASE cloudDB02 CHARACTER SET UTF8;
 
USE cloudDB02;
 
CREATE TABLE dept
(
  deptno BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  dname VARCHAR(60),
  db_source   VARCHAR(60)
);
 
INSERT INTO dept(dname,db_source) VALUES('开发部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('人事部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('财务部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('市场部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('运维部',DATABASE());
 
SELECT * FROM dept;
</code></pre>
<pre><code class="language-sql">DROP DATABASE IF EXISTS cloudDB03;
 
CREATE DATABASE cloudDB03 CHARACTER SET UTF8;
 
USE cloudDB03;
 
CREATE TABLE dept
(
  deptno BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  dname VARCHAR(60),
  db_source   VARCHAR(60)
);
 
INSERT INTO dept(dname,db_source) VALUES('开发部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('人事部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('财务部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('市场部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('运维部',DATABASE());
 
SELECT * FROM dept;
</code></pre>
<p>3）pom</p>
<p>8002、8003跟8001保持一致</p>
<p>4）yml</p>
<p>备忘</p>
<ul>
<li>端口：8002、8003</li>
<li>数据库链接：jdbc:mysql://localhost:3306/cloudDB01 或 cloudDB02 或 cloudDB03</li>
<li>对外暴露的统一的服务实例名<code>microservicecloud-dept</code></li>
</ul>
<p><img src="77766EDE8F9543F7B85D86E7122BD43A" alt="image"></p>
<p>5）测试</p>
<p>启动</p>
<ul>
<li>microservicecloud-eureka-7001</li>
<li>microservicecloud-eureka-7002</li>
<li>microservicecloud-provider-dept-8001</li>
<li>microservicecloud-provider-dept-8002</li>
</ul>
<blockquote>
<p>由于只有8G内存，只启动了以上4个</p>
</blockquote>
<p>测试8001、8002是否可以访问：</p>
<ul>
<li>http://localhost:8001/dept/list</li>
<li>http://localhost:8002/dept/list</li>
</ul>
<p>最后，启动消费者：<code>microservicecloud-consumer-dept-80</code>，测试消费接口：http://localhost/consumer/dept/list</p>
<p>可以看到数据会轮流从cloudDB01、cloudDB02库中获取</p>
<p>6）总结</p>
<p>Ribbon负载均衡<strong>默认采用轮询模式</strong>（轮流来）</p>
<p>自我总结：三个服务提供者的实例名相同，都是<code>microservicecloud-dept</code>，但各自对应的数据库不同（cloudDB01、cloudDB02、cloudDB03），我认为是为了测试用，不具有真实项目作用 —— 20191116</p>
<h1 id="ribbon的负载均衡策略">Ribbon的负载均衡策略</h1>
<p>Ribbon的负载均衡的核心是IRule，IRule提供以下策略：</p>
<p><img src="https://oscimg.oschina.net/oscnet/up-e6e347d5bb2483af9678ea774e7f7ad70b7.png" alt="IRule"></p>
<p>如何使用以上策略？</p>
<pre><code class="language-java">@Configuration
public class ConfigBean {

    // 指定策略
    @Bean
    public IRule myRule()
    {
        //return new RoundRobinRule();
        //return new RandomRule();//达到的目的，用我们重新选择的随机算法替代默认的轮询。
        return new RetryRule();
    }
}
</code></pre>
<h1 id="自定义ribbonirule策略">自定义Ribbon——IRule策略</h1>
<p>步骤：</p>
<p>1）在主启动类添加<code>@RibbonClient</code>注解，指定自定义Ribbon的配置类</p>
<pre><code class="language-java">@SpringBootApplication
@EnableEurekaClient
//在启动该微服务的时候就能去加载我们的自定义Ribbon配置类，从而使配置生效
@RibbonClient(name=&quot;MICROSERVICECLOUD-DEPT&quot;,configuration=MySelfRule.class)
public class DeptConsumer80_App
{
	public static void main(String[] args)
	{
		SpringApplication.run(DeptConsumer80_App.class, args);
	}
}
</code></pre>
<p>2）新建MySelfRule类</p>
<p>注意：MySelfRule类<strong>不能跟启动类放在同一个包及子包</strong>中（官方文档：https://cloud.spring.io/spring-cloud-static/Greenwich.SR4/single/spring-cloud.html#_customizing_the_ribbon_client）</p>
<p>总结：MySelfRule配置类中的@Bean要继承AbstractLoadBalancerRule类</p>

    </div>
    <div class="article-footer">
<blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    <li class="post-copyright-link hidden-xs">
      <strong>Permalink: </strong>
      <a href="https://rulerLwx.gitee.io/2020/07/java-framework-springcloud-3/" title="Java-framework-SpringCloud-3" target="_blank" rel="external">https://rulerLwx.gitee.io/2020/07/java-framework-springcloud-3/</a>
    </li>
    <li class="post-copyright-license">
      <strong>License：</strong><a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN</a>
    </li>
  </ul>
</blockquote>

<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://gitee.com/rulerLwx" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="https://rulerLwx.gitee.io/avatar.png" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://gitee.com/rulerLwx" target="_blank"><span class="text-dark">rulerLwx</span><small class="ml-1x">thinking...</small></a></h3>
        <div>Good Good Study, Day Day Up~</div>
      </div>
    </figure>
  </div>
</div>
    </div>
  </article>
<section id="comments">
    <div id="vcomments"></div>
</section>

</div><nav class="bar bar-footer clearfix" data-stick-bottom>
    <div class="bar-inner">
        <ul class="pager pull-left">
            <li class="prev">
                <a href="https://rulerLwx.gitee.io/2020/07/java-framework-springcloud-4/" title="Java-framework-SpringCloud-4"><i
                        class="icon icon-angle-left"
                        aria-hidden="true"></i><span>&nbsp;&nbsp;Older</span></a>
            </li>
            <li class="next">
                <a href="https://rulerLwx.gitee.io/2020/07/java-framework-springcloud-2-eureka/"
                    title="Java-framework-SpringCloud-2-Eureka"><span>Newer&nbsp;&nbsp;</span><i
                        class="icon icon-angle-right" aria-hidden="true"></i></a>
            </li>
            
            <li class="toggle-toc">
                <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false"
                    title="Catalogue" role="button">
                    <span>[&nbsp;</span><span>Catalogue</span>
                    <i class="text-collapsed icon icon-anchor"></i>
                    <i class="text-in icon icon-close"></i>
                    <span>]</span>
                </a>
            </li>
        </ul>
        <div class="bar-right">
            <div class="share-component" data-sites="weibo,qq,wechat"
                data-mobile-sites="weibo,qq,qzone"></div>
        </div>
    </div>
</nav>

</main><footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
<ul class="social-links">
    <li><a href="https://gitee.com/rulerLwx" target="_blank" title="gitee" data-toggle=tooltip data-placement=top >
            <i class="icon icon-gitee"></i></a></li>
    <li><a href="https://github.com/wolf-lea" target="_blank" title="github" data-toggle=tooltip data-placement=top >
            <i class="icon icon-github"></i></a></li>
</ul>
  <div class="copyright">
    &copy;2020  -
    2020
    <div class="publishby">
        Theme by <a href="https://github.com/xiaoheiAh" target="_blank"> xiaoheiAh </a>base on<a href="https://github.com/xiaoheiAh/hugo-theme-pure" target="_blank"> pure</a>.
    </div>
  </div>
</footer>

<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_SVG"></script>
<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
            showMathMenu: false, //disables context menu
            tex2jax: {
            inlineMath: [ ['$','$'], ['\\(','\\)'] ]
           }
    });
</script>


<script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>
<script>
    window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/highlight.min.js"></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/python.min.js" defer></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/javascript.min.js" defer></script><script>
    hljs.configure({
        tabReplace: '    ', 
        classPrefix: ''     
        
    })
    hljs.initHighlightingOnLoad();
</script>
<script src="https://rulerLwx.gitee.io/js/application.min.bdeb64b910570b6c41badc6a05b7afb0c8ad9efd8525de3c7257d59e786326a3.js"></script>
<script src="https://rulerLwx.gitee.io/js/plugin.min.51ff8c7317566f82259170fa36e09c4493adc9b9378b427a01ad3f017ebac7dd.js"></script>

<script>
    (function (window) {
        var INSIGHT_CONFIG = {
            TRANSLATION: {
                POSTS: 'Posts',
                PAGES: 'Pages',
                CATEGORIES: 'Categories',
                TAGS: 'Tags',
                UNTITLED: '(Untitled)',
            },
            ROOT_URL: 'https:\/\/rulerLwx.gitee.io',
            CONTENT_URL: 'https:\/\/rulerLwx.gitee.io\/searchindex.json ',
        };
        window.INSIGHT_CONFIG = INSIGHT_CONFIG;
    })(window);
</script>
<script type="text/javascript" src="https://rulerLwx.gitee.io/js/insight.min.a343cd9a5a7698336b28ef3a7c16a3a1b1d2d5fb17dc8ed04022bbe08cc5459073a15bdafa3a8a58cdd56080784bdd69fa70b1ae8597565c799c57ed00f0e120.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.min.js"></script>
<script>
    tocbot.init({
        
        tocSelector: '.js-toc',
        
        contentSelector: '.js-toc-content',
        
        headingSelector: 'h1, h2, h3',
        
        hasInnerContainers: true,
    });
</script>

<script src="https://cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine"></script>
<script type="text/javascript">
    var GUEST = ['nick', 'mail', 'link'];
    var meta = 'nick,mail';
    meta = meta.split(',').filter(function (item) {
        return GUEST.indexOf(item) > -1;
    });
    new Valine({
        el: '#vcomments',
        verify: null ,
        notify: null ,
        appId: 'IyAB0PSPRazTPDxitO1ddQ7O-gzGzoHsz',
        appKey: '5rBJTq4KidYF33eXwvRVhtEH',
        placeholder: 'enjoy~',
        avatar: 'mm',
        meta: meta,
        pageSize: '10' || 10,
        visitor: false 
});
</script>

  </body>
</html>
